package com.alisls.activiti.service.handler;

import com.alisls.activiti.service.util.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义认证失败处理器
 *
 * @author Ke Wang
 */
@Component
public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Resource
    private ObjectMapper objectMapper;

    /**
     * 认证失败处理器
     * @param request 请求
     * @param response 响应
     * @param exception 异常
     * @throws IOException IO异常
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception)
            throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        Result result = Result.build(HttpStatus.UNAUTHORIZED.value(), exception.getMessage());
        String json = objectMapper.writeValueAsString(result);
        response.getWriter().write(json);
    }

}
